<?php


namespace app\validate\api;


use app\exception\ParameterException;
use think\facade\Validate;

class OrderPlace extends BaseValidate
{
    protected $rule = [
        'products' =>   'checkProducts'
    ];
    protected $singleRule = [
        'product_id'=>'require|isPositiveInteger',
        'count'=>'require|isPositiveInteger'
    ];

    /**
     * @param        $values
     * @param string $rule
     * @param string $data
     * @param string $field
     *
     * @return bool
     * @throws ParameterException
     */
    protected function checkProducts($values,$rule='',$data='',$field=''): bool
    {
        if(!is_array($values)){
            throw new ParameterException([
                'msg'=>'商品参数不正确'
            ]);
        }
        if(empty($values)){
            throw new ParameterException([
                'msg'=>'商品列表不能为空'
            ]);
        }
        foreach($values as $k=>$v){
            $this->checkProduct($v);
        }
        return true;
    }

    /**
     * @param $value
     *
     * @throws ParameterException
     */
    protected function checkProduct($value,$rule='',$data='',$field=''){
        $validate = new OrderPlace();
        $result = $validate->rule($this->singleRule)->check($value);
        if(!$result){
            throw new ParameterException([
                'msg'=>'商品列表参数错误'
            ]);
        }
    }
}